package com.glq1218.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.glq1218.domain.Interval;
import com.glq1218.domain.IntervalStr;
import com.glq1218.domain.PaginationParam;
import com.glq1218.user.entity.User;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @author glq1218
 * @description 业务层通用工具类
 * @since 2023/4/11 14:38
 */
public class ServiceUtils {
    /**
     * 字符串转LocalDateTime
     *
     * @param str 时间字符串
     * @return LocalDataTime对象
     */
    public static LocalDateTime getLocalDateTimeByString(String str) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(str, df);
    }

    /**
     * 把时间间隔字符串转为 LocalDateTime
     *
     * @param intervalStr 时间间隔字符串对象
     * @return 时间间隔 LocalDateTime 对象
     */
    public static Interval getInterval(IntervalStr intervalStr) {
        Interval interval = new Interval();
        if (StringUtils.hasText(intervalStr.getUpdatedAtStart()) && StringUtils.hasText(intervalStr.getUpdatedAtEnd())) {
            interval.setUpdatedAtStart(getLocalDateTimeByString(intervalStr.getUpdatedAtStart() + " 00:00:00"));
            interval.setUpdatedAtEnd(getLocalDateTimeByString(intervalStr.getUpdatedAtEnd() + " 23:59:59"));
        }
        if (StringUtils.hasText(intervalStr.getCreatedAtStart()) && StringUtils.hasText(intervalStr.getCreatedAtEnd())) {
            interval.setCreatedAtStart(getLocalDateTimeByString(intervalStr.getCreatedAtStart() + " 00:00:00"));
            interval.setCreatedAtEnd(getLocalDateTimeByString(intervalStr.getCreatedAtEnd() + " 23:59:59"));
        }
        return interval;
    }

    /**
     * 获取mybatis-plus分页对象
     *
     * @param paginationParam 分页参数
     * @return mybatis-plus分页对象
     */
    public static <T> Page<T> getPage(PaginationParam paginationParam) {
        if (Objects.isNull(paginationParam.getCurrent())) {
            paginationParam.setCurrent(1);
        }
        if (Objects.isNull(paginationParam.getPageSize())) {
            paginationParam.setPageSize(10);
        }
        return new Page<>(paginationParam.getCurrent(), paginationParam.getPageSize());
    }

}
